package com.example.commonlib.commonutil;

import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class BitmapUtil2 {

    public static final int IO_BUFFER_SIZE = 8 * 1024;
    private static Bitmap.CompressFormat mCompressFormat = Bitmap.CompressFormat.JPEG;
    private static int mCompressQuality = 100;

    public static String saveMyBitmap(String dirStr, String nameStr,Bitmap mBitmap, Bitmap.CompressFormat type, int quliat) throws IOException {
        if (mBitmap == null)
            return "";

        File file = new File(dirStr);
        if (!file.exists()){
            file.mkdirs();
        }
        file = null;

        File bitmapFile = new File(dirStr + nameStr);


        FileOutputStream fos = new FileOutputStream(bitmapFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);


        mBitmap.compress(type, quliat, bos);
        bos.flush();
        bos.close();

        return bitmapFile.getAbsolutePath();
    }

    /**
     * 处理图片
     *
     * @param bm        所要转换的bitmap
     * @param newWidth  新的宽
     * @param newHeight 新的高
     * @return 指定宽高的bitmap
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight;
        if (newHeight != 0) {
            scaleHeight = ((float) newHeight) / height;
        }else{
            scaleHeight =  scaleWidth;
        }
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片   www.2cto.com
        bm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return bm;
    }



    public static Bitmap decodeFile(InputStream input, String cropUrl, int maxWidth, int maxHeight) {
        if (input == null) {
            return null;
        }
        Bitmap boundBmp = null;
        Bitmap scaleBmp = null;
        byte[] data = readStream(input);
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            boundBmp = BitmapFactory.decodeByteArray(data, 0, data.length, o);
            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 50; // 平板上适当高清点
            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            if (width_tmp < maxWidth){
                o.inSampleSize = 1;
                o.inJustDecodeBounds = false;
                scaleBmp =  zoomImg(BitmapFactory.decodeByteArray(data, 0, data.length, o),maxWidth,0);
            }else {
                int scale = 1;
                while (true) {
                    if (width_tmp <= maxWidth && height_tmp <= maxHeight
                            ) {
                        break;
                    }

                    width_tmp *= 0.25;
                    height_tmp *= 0.25;
//                width_tmp = maxWidth;
                    scale *= 2;

                }
                // decode with inSampleSize
                o.inSampleSize = scale;
                o.inJustDecodeBounds = false;
                scaleBmp = BitmapFactory.decodeByteArray(data, 0, data.length, o);
                MLog.e("util", "tepWidth:" + width_tmp + "height:" + height_tmp);
            }
            if (cropUrl != null)
                writeBitmapToFile(scaleBmp, cropUrl);
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            Util.setLog("BitmapUtil","decodeBitmapOOM");
            e.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (boundBmp != null)
                boundBmp.recycle();
        }
        return scaleBmp;
    }


    /**
     * 根据路径获取图片宽高（不实际加载图片）
     * @param path
     * @return
     */
    public static int[] getBitmapSize(String path){
        InputStream inputStream =  path2Input(path);
        int[] result = new int[2];
        if (inputStream == null)
            return null;
        byte[] data = readStream(inputStream);

        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, o);
        result[0] = o.outWidth;
        result[1] = o.outHeight;


        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;

    }

    /**
     * 讲路径转换成bitmap
     * @param path
     * @return
     */
    public static Bitmap path2Bitmap(String path){
        try {
            InputStream inputStream = path2Input(path);
            if (inputStream != null)
            {
                byte[] bytes = readStream(inputStream);
                if (bytes != null)
                {
                    return byteArray2Bitmap(bytes);
                }
            }
        }
        catch (Exception ex)
        {
            return null;
        }

        return null;
    }

    /**
     * 讲路径转换成bitmap
     * @param path
     * @return
     */
    public static Bitmap path2Bitmap(String path, int maxWidth, int maxHeight){
        return decodeFile(path2Input(path), null, maxWidth, maxHeight);
    }



    /**
     * 将路径转换成流
     * @param path
     * @return
     */

    public static InputStream path2Input(String path){

        InputStream inputStream = null;
        File file = new File(path);
        if (file.exists()){
            try {
                inputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        return inputStream;
    }



    /**
     * 将byte数组转换成bitmap
     * @param bytes
     * @return
     */
    public static Bitmap byteArray2Bitmap(byte[] bytes){

        if (bytes != null && bytes.length>0)
            return  BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        return null;
    }



    public static byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }


    public static String bitmap2Base64(Bitmap bitmap){
        return  Base64.encode(bitmap2Bytes(bitmap));
    }

    public static Bitmap base642Bitmap(String base64Str){
        return  byteArray2Bitmap(Base64.decode(base64Str));
    }


    /**
     * 得到图片字节流 数组大小 为解决网络inputstream获取不到bitmap的bug
     */
    private static byte[] readStream(InputStream inStream) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len = 0;
        try {
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return outStream.toByteArray();
    }

    public static boolean writeBitmapToFile(Bitmap bitmap, String path)
            throws IOException, FileNotFoundException {
        if (bitmap == null)
            return false;
        OutputStream out = null;
        try {
            File file = new File(path);
            out = new BufferedOutputStream(new FileOutputStream(file),
                    IO_BUFFER_SIZE);
            return bitmap.compress(mCompressFormat, mCompressQuality, out);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    /**
     * 生成图标局部高斯模糊并且与imageview绑定
     * @param imgeView
     * @param bitmap
     * @param radius
     * @param x
     * @param y
     * @param width
     * @param height
     */
//    public static void setBlurToImgeView(ImageView imgeView, Bitmap bitmap, int radius, int round, int x, int y, int width, int height){
//        FastBlur fastBlur = new FastBlur();
//        RoundedBitmapDisplayer roundedBitmapDisplayer = new RoundedBitmapDisplayer(round,0);
//        Bitmap finalBitmap = fastBlur.fastblur(bitmap,radius,imgeView,x, y, width, height);
//        roundedBitmapDisplayer.display(finalBitmap, (new ImageViewAware(imgeView)), LoadedFrom.MEMORY_CACHE);
//    }


    /**
     * 生成图标局部高斯模糊并且与imageview绑定
//     * @param imgeView
//     * @param radius
//     * @param x
//     * @param y
//     * @param width
//     * @param height
     */
//    public static void setBlurToImgeView(Activity activity, final ImageView imgeView, final ImageView fadeOutIv, final View view, final int radius, final int x, final int y, final int width, final int height){
//
//        final Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.RGB_565);
//        final FastBlur fastBlur = new FastBlur();
//        final FadeInBitmapDisplayer fadeInBitmapDisplayer = new FadeInBitmapDisplayer(300);
//
//        final Canvas canvas = new Canvas(bitmap);
//
//        activity.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                view.draw(canvas);
//                final Bitmap finalBitmap = fastBlur.fastblur(bitmap, radius, imgeView, x, y, width, height);
//                fadeOutIv.setImageDrawable(imgeView.getDrawable());
//                fadeOutIv.setVisibility(View.VISIBLE);
//                fadeInBitmapDisplayer.display(finalBitmap, (new ImageViewAware(imgeView)), LoadedFrom.MEMORY_CACHE);
//                fadeOutAnimation(fadeOutIv, 500);
//                bitmap.recycle();
//            }
//        });
//    }


    private static void fadeOutAnimation(ImageView imageView, long durationMillis){
        AlphaAnimation fadeImage = new AlphaAnimation(1.0f, 0.0f);
        fadeImage.setDuration(durationMillis);
        fadeImage.setInterpolator(new DecelerateInterpolator());
        imageView.startAnimation(fadeImage);
        imageView.setVisibility(View.GONE);
    }


    /**
     * 将图片有颜色的地方转换成新的颜色
     * @param drawable
     * @param colors
     * @return
     */
    public static Drawable tintDrawable(Drawable drawable, ColorStateList colors) {
        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTintList(wrappedDrawable, colors);
        return wrappedDrawable;
    }






    public static Bitmap getMosaicsBitmaps(Bitmap bmp, double precent) {
        long start = System.currentTimeMillis();
        int bmpW = bmp.getWidth();
        int bmpH = bmp.getHeight();
        int[] pixels = new int[bmpH * bmpW];
        bmp.getPixels(pixels, 0, bmpW, 0, 0, bmpW, bmpH);
        int raw = (int) (bmpW * precent);
        int unit;
        if (raw == 0) {
            unit = bmpW;
        } else {
            unit = bmpW / raw; //原来的unit*unit像素点合成一个，使用原左上角的值
        }
//        if (unit >= bmpW || unit >= bmpH) {
//            return getMosaicsBitmap(bmp, precent);
//        }
        for (int i = 0; i < bmpH; ) {
            for (int j = 0; j < bmpW; ) {
                int leftTopPoint = i * bmpW + j;
                for (int k = 0; k < unit; k++) {
                    for (int m = 0; m < unit; m++) {
                        int point = (i + k) * bmpW + (j + m);
                        if (point < pixels.length) {
                            pixels[point] = pixels[leftTopPoint];
                        }
                    }
                }
                j += unit;
            }
            i += unit;
        }
        long end = System.currentTimeMillis();
        return Bitmap.createBitmap(pixels, bmpW, bmpH, Bitmap.Config.RGB_565);
    }

    /**
     *   Drawable  转  Bitmap
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


}